# koroFileHeader at Yungoal acer
# Create: 2021-05-20 14:04:46
# LastEdit: 2021-05-24 13:53:57
"""说明暂无"""
__author__ = '749B'

import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
sys.path.append(BASE_DIR)

import textwrap

# pylint: disable = import-error
from azure_client import Azure_Client
from msrestazure.azure_cloud import AZURE_CHINA_CLOUD

def main():
    import pprint
    client = Azure_Client(AZURE_CHINA_CLOUD)
    subscription_id = client.get_subscriptionid_by_name(SUB_NAME)
    resource_group_name = RESOURCE_GROUP_NAME
    vm_name = VM_NAME
    script = SCRIPT
    res = client.runcmd_onestep(
        subscription_id, resource_group_name, vm_name, script, 
        parameters=SCRIPT_ARGS,
        is_linux=IS_LINUX, 
        report=True,
        wait=WAIT,
        )
    if res[0]:
        # 命令执行完成
        pprint.pp(res[1].json())
        '''
        Windows 的返回结果：
        {'startTime': '2021-05-20T08:51:58.8606138+00:00',
        'endTime': '2021-05-20T08:52:29.2102968+00:00',
        'status': 'Succeeded',
        'properties': {'output': {'value': [{'code': 'ComponentStatus/StdOut/succeeded',
                                            'level': 'Info',
                                            'displayStatus': 'Provisioning succeeded',
                                            'message': 'Thursday, May 20, 2021 '
                                                        '8:52:10 AM\n'
                                                        '\n'},
                                            {'code': 'ComponentStatus/StdErr/succeeded',
                                            'level': 'Info',
                                            'displayStatus': 'Provisioning succeeded',
                                            'message': ''}]}},
        'name': '01df2589-8af3-496b-9004-b2d828d6932c'}

        Linux 的返回结果
        {'startTime': '2021-05-23T07:13:40.9387012+00:00',
        'endTime': '2021-05-23T07:14:05.0343358+00:00',
        'status': 'Succeeded',
        'properties': {'output': {'value': [{'code': 'ProvisioningState/succeeded',
                                            'level': 'Info',
                                            'displayStatus': 'Provisioning succeeded',
                                            'message': 'Enable succeeded: \n'
                                                        '[stdout]\n'
                                                        '2021年 05月 23日 星期日 15:13:51 '
                                                        'CST\n'
                                                        '\n'
                                                        '[stderr]\n'}]}},
        'name': '099ad8f2-bacc-442c-b6f7-c8ae9dff81de'}
        '''
    else:
        # 命令未执行完成
        pprint.pp(res[1].json())
        '''
        {'error': {'code': 'Conflict',
                'message': 'Run command extension execution is in progress. Please '
                            'wait for completion before invoking a run command.'}}
        '''


if __name__ == "__main__":

    ENV_FILE = '.env/dev_cn.env'
    SUB_NAME = 'Yungoal_SI'
    RESOURCE_GROUP_NAME = 'steed-dev'
    VM_NAME = 'winhost3'    
    IS_LINUX = False

    # 无参数
    SCRIPT1 = ['date']
    SCRIPT_ARGS1 = None
    # 关键字参数
    SCRIPT2 = textwrap.dedent("""\
        param(
            [string]$arg1,
            [string]$arg2
        )
        Write-Host This is a sample script with parameters $arg1 and $arg2
        """).splitlines()
    SCRIPT_ARGS2 = [{'name': 'arg1', 'value': 'v1'}, {'name': 'arg2', 'value': 'VALUE2'}]
    # 位置参数测试不出来，自己生成代码
    SCRIPT3 = textwrap.dedent("""\
        function check($service) {
            $result = Get-Service $service -ErrorAction SilentlyContinue
            if ($?) {
                $result | %{$_.Status}
            } else {
                Write-Host NotExist
            }
        }
        
        """).splitlines()
    names = ["Dhcp", "Kaspersky Security Center 11 Network Agent", "Kaspersky Security Exploit Prevention Service", "Kaspersky Security Service"]
    for n in names:
        SCRIPT3.append('check("%s")' % n)
    SCRIPT_ARGS3 = None

    SCRIPT = SCRIPT1
    SCRIPT_ARGS = SCRIPT_ARGS1
    
    WAIT = 20

    from environs import Env
    env = Env()
    env.read_env(ENV_FILE)
    main()


    